<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="模具编码" prop="accountId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.accountId" placeholder="请选择模具"
          check-strictly filterable>
          <el-option v-for="dict in accountList" :key="dict.id" :label="dict.code" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="图号" prop="drawingNoId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.drawingNoId"
          placeholder="请选择图号" check-strictly filterable>
          <el-option v-for="dict in drawingNoList" :key="dict.id" :label="dict.drawingNo" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="复检类型" prop="recheckId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.recheckId"
          placeholder="请选择复检类型" check-strictly filterable>
          <el-option v-for="dict in recheckTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="任务状态" prop="status">
        <el-select @change="handleQuery" v-model="queryParams.status" placeholder="请选择任务状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_RECHECK_TOBE_STATUS)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mold:recheck-tobe:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mold:recheck-tobe:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['mold:recheck-tobe:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" @selection-change="handleRowCheckboxChange"
      :row-style="rowStyle" :row-class-name="rowClassName" border resizable>
      <el-table-column type="selection" width="55" />
      <el-table-column label="图号" align="center" prop="drawingNo" min-width="90" />
      <el-table-column label="模具" align="center" prop="name" min-width="90" />
      <el-table-column label="编码" align="center" prop="code" min-width="120" />
      <el-table-column label="复检类型" align="center" prop="recheckCategory" min-width="90" />
      <el-table-column label="添加方式" align="center" prop="ifTmp" min-width="90">
        <template #default="scope">
          <span v-if="scope.row.ifTmp === 1">手动</span>
          <span v-else-if="scope.row.ifTmp === 0">自动</span>
          <span v-else>{{ scope.row.ifTmp }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次复检日期" align="center" prop="lastRecheckTime" :formatter="dateFormatter"
        min-width="180" />
      <el-table-column label="下次复检日期" align="center" prop="nextRecheckTime" :formatter="dateFormatter"
        min-width="180" />
      <el-table-column label="任务状态" align="center" prop="status" min-width="90">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_RECHECK_TOBE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="170px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleDispatch(scope.row.id)" v-if="scope.row.status === 1">
            派工
          </el-button>
          <el-button link type="primary" @click="handleCancelDispatch(scope.row.id)" v-if="scope.row.status === 2">
            撤销
          </el-button>
          <el-button link type="primary" @click="handleAudit(scope.row)" v-if="scope.row.status === 5">
            审核
          </el-button>
          <el-button link type="primary" @click="handleJump(scope.row.id)" v-if="scope.row.status >= 2">
            跳转
          </el-button>
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['mold:recheck-tobe:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mold:recheck-tobe:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RecheckTobeForm ref="formRef" @success="getList" />

  <!-- 派工弹窗 -->
  <RecheckTobeDispatch ref="dispatchFormRef" @success="getList" />

  <!-- 审核 -->
  <RecheckTobeAudit ref="auditFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { defaultProps, handleTree } from '@/utils/tree'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RecheckTobeApi, RecheckTobe } from '@/api/mold/rechecktobe'
import RecheckTobeForm from './RecheckTobeForm.vue'
import RecheckTobeAudit from './RecheckTobeAudit.vue'
import RecheckTobeDispatch from './RecheckTobeDispatch.vue'
import { DrawingNoApi } from '@/api/mold/drawingno'
import { AccountApi } from '@/api/mold/account'
import { RecheckCategoryApi } from '@/api/mold/recheckcategory'
import { useRouter } from 'vue-router'

/** 待复检 列表 */
defineOptions({ name: 'RecheckTobe' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()

const loading = ref(true) // 列表的加载中
const list = ref<RecheckTobe[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  accountId: undefined,
  drawingNoId: undefined,
  recheckId: undefined,
  lastRecheckTime: [],
  ifTmp: undefined,
  status: undefined,
  taskId: undefined,
  itemId: undefined,
  createTime: [],
  remindF: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const drawingNoList = ref([])
const accountList = ref([])
const recheckTypeList = ref([])

/** 获得图号列表 */
const getDrawingNoList = async () => {
  drawingNoList.value = []
  const data = await DrawingNoApi.getDrawingNoAll()
  drawingNoList.value = data
}

/** 获取模具台账列表 */
const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}

/** 获取复检类型列表 */
const getRecheckTypeList = async () => {
  recheckTypeList.value = []
  const data = await RecheckCategoryApi.getRecheckCategoryAll()
  recheckTypeList.value = data
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RecheckTobeApi.getRecheckTobePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RecheckTobeApi.deleteRecheckTobe(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除待复检 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RecheckTobeApi.deleteRecheckTobeList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RecheckTobe[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecheckTobeApi.exportRecheckTobe(queryParams)
    download.excel(data, '待复检.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 派工操作
const dispatchFormRef = ref()
const handleDispatch = (id: number) => {
  dispatchFormRef.value.open(id)
  handleQuery()
}

// 撤销派工操作
const handleCancelDispatch = (id: number) => {
  // 弹窗提示，撤销后重置派工状态，同时删除复检任务？
  message.confirm('确认要撤销此任务,同时删除该设备复检任务吗？').then(async () => {
    await RecheckTobeApi.cancelDispatchRecheckTobe(id).then(() => {
      message.success('撤销成功')
    }).finally(() => {
      handleQuery()
    })
  })
}

// 审核操作
const auditFormRef = ref()
const handleAudit = (row: RecheckTobe) => {
  auditFormRef.value.open(row.id, row.taskId)
  handleQuery()
}

// 跳转到复检任务方法
const handleJump = (id: number) => {
  router.push({ name: 'mold/rechecktask/index', query: { accountId: id } })
}

// 行样式
const rowStyle = ({ row }: { row: any }) => {
  const bgColor = row.color || ''
  return {
    backgroundColor: bgColor + ' !important' // 添加 !important 提高优先级
  }
}

// 行类名
const rowClassName = ({ row }: { row: any }) => {
  if (row.color) {
    return 'colored-row'
  }
  return ''
}

/** 初始化 **/
onMounted(() => {
  getAccountList()
  getDrawingNoList()
  getRecheckTypeList()
  getList()
})
</script>